package com.wenye.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wenye.Util.JWTUtil;
import com.wenye.entity.User;
import com.wenye.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

//@RestController
@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/test")
    public String test(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        String token = request.getHeader("token");
        for(Cookie a:cookies) {
            if(a.getName().equals("token")){
                token=a.getValue();
            }
        }
        DecodedJWT verify = JWTUtil.Verify(token);
        System.out.printf("### new test request\n->ID:%s username:%s\n",verify.getClaim("ID"),verify.getClaim("username"));
        System.out.printf("->token:%s\n",token);
        map.put("state",true);
        map.put("msg","认证成功");
        return "test";
    }

    @PostMapping("/user/login")
    public String login(User user, HttpServletResponse response,HttpServletRequest request){
        user.setId("1");
        Map<String, Object> map = new HashMap<>();
        try{
            System.out.printf("### new login request\n->username:%s password:%s\n",user.getUsername(),user.getPassword());
            User userDB = userService.login(user);
            Map<String,String> payload = new HashMap<>();
            payload.put("ID",userDB.getId());
            payload.put("username",userDB.getUsername());
            // 生成JWT令牌
            String token = JWTUtil.getToken(payload);
            Cookie cookie = new Cookie("token",token);
            cookie.setDomain("localhost");
            cookie.setPath("/");
            response.addCookie(cookie);
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);

            // 取出来源的url地址，以便登录成功后的跳转
            String refererUrl = request.getHeader("Referer");
            String realRefererUrl = refererUrl.substring(refererUrl.indexOf("?")+1);
            System.out.printf("### Login Success!\n->username:%s password:%s\n",user.getUsername(),user.getPassword());
            System.out.printf("->The destination url is '%s'",realRefererUrl);
            if(realRefererUrl.substring(realRefererUrl.length()-5).equals("login")){
                //refer to Web1.
            }
            return "redirect:"+realRefererUrl;
        }catch(Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
            System.out.printf("### Error,Login failed!\n->username:%s password:%s\n",user.getUsername(),user.getPassword());
            System.out.printf("->msg:%s",e.getMessage());
        }
        return "login";
    }
    @GetMapping("/user/login")
    public String toLogin(){
        return "login";
    }
}
